from typing import Dict, Any, List, Optional
from sqlalchemy.orm import Session
from sqlalchemy import and_, or_, desc, func

from models import Merchant
import schemas

def get_merchant_list(db: Session, filters: Dict[str, Any], page_num: int, page_size: int) -> Dict[str, Any]:
    """
    获取商户列表
    
    Args:
        db: 数据库会话
        filters: 过滤条件
        page_num: 页码
        page_size: 每页记录数
        
    Returns:
        商户列表
    """
    # 构建查询条件
    query = db.query(Merchant)
    
    # 应用过滤条件
    for key, value in filters.items():
        if key == "name" and value:
            # 名称模糊查询
            query = query.filter(Merchant.name.like(f"%{value}%"))
        elif key == "code" and value:
            # 编码模糊查询
            query = query.filter(Merchant.code.like(f"%{value}%"))
        elif hasattr(Merchant, key):
            query = query.filter(getattr(Merchant, key) == value)
    
    # 获取总记录数
    total = query.count()
    
    # 分页
    query = query.order_by(Merchant.id)
    query = query.offset((page_num - 1) * page_size).limit(page_size)
    
    # 执行查询
    merchants = query.all()
    
    # 构建返回数据
    merchant_list = []
    for merchant in merchants:
        merchant_list.append({
            "merchantId": merchant.id,
            "name": merchant.name,
            "code": merchant.code,
            "contactPerson": merchant.contact_person,
            "contactPhone": merchant.contact_phone,
            "status": merchant.status,
            "createTime": merchant.created_at.strftime("%Y-%m-%d %H:%M:%S")
        })
    
    return {
        "total": total,
        "pageNum": page_num,
        "pageSize": page_size,
        "list": merchant_list
    }

def get_merchant_by_id(db: Session, merchant_id: int) -> Optional[Merchant]:
    """
    根据ID获取商户
    
    Args:
        db: 数据库会话
        merchant_id: 商户ID
        
    Returns:
        商户记录
    """
    return db.query(Merchant).filter(Merchant.id == merchant_id).first()

def create_merchant(db: Session, merchant_data: Dict[str, Any]) -> Merchant:
    """
    创建商户
    
    Args:
        db: 数据库会话
        merchant_data: 商户数据
        
    Returns:
        创建的商户
    """
    # 创建商户
    merchant = Merchant(
        name=merchant_data["name"],
        code=merchant_data["code"],
        contact_person=merchant_data.get("contact_person"),
        contact_phone=merchant_data.get("contact_phone"),
        address=merchant_data.get("address"),
        status=merchant_data.get("status", 1),
        remark=merchant_data.get("remark")
    )
    
    db.add(merchant)
    db.commit()
    db.refresh(merchant)
    
    return merchant

def create_merchant_with_id(db: Session, merchant_data: Dict[str, Any]) -> Merchant:
    """
    使用指定ID创建商户
    
    Args:
        db: 数据库会话
        merchant_data: 商户数据，包含id字段
        
    Returns:
        创建的商户
    """
    # 检查ID是否存在
    if db.query(Merchant).filter(Merchant.id == merchant_data["id"]).first():
        # 如果ID已存在，直接返回该商户
        return db.query(Merchant).filter(Merchant.id == merchant_data["id"]).first()
    
    # 创建带有指定ID的商户
    merchant = Merchant(
        id=merchant_data["id"],
        name=merchant_data["name"],
        code=merchant_data["code"],
        contact_person=merchant_data.get("contact_person"),
        contact_phone=merchant_data.get("contact_phone", ""),
        address=merchant_data.get("address", ""),
        status=merchant_data.get("status", 1),
        remark=merchant_data.get("remark", "")
    )
    
    db.add(merchant)
    
    try:
        db.commit()
        db.refresh(merchant)
    except Exception as e:
        db.rollback()
        raise e
    
    return merchant

def update_merchant(db: Session, merchant_id: int, merchant_data: Dict[str, Any]) -> Optional[Merchant]:
    """
    更新商户
    
    Args:
        db: 数据库会话
        merchant_id: 商户ID
        merchant_data: 商户数据
        
    Returns:
        更新后的商户
    """
    # 获取商户
    merchant = db.query(Merchant).filter(Merchant.id == merchant_id).first()
    if not merchant:
        return None
    
    # 更新商户属性
    for key, value in merchant_data.items():
        if hasattr(merchant, key) and value is not None:
            setattr(merchant, key, value)
    
    db.commit()
    db.refresh(merchant)
    
    return merchant

def delete_merchant(db: Session, merchant_id: int) -> bool:
    """
    删除商户
    
    Args:
        db: 数据库会话
        merchant_id: 商户ID
        
    Returns:
        是否成功
    """
    merchant = db.query(Merchant).filter(Merchant.id == merchant_id).first()
    if not merchant:
        return False
    
    # 实际上可能不会真的删除记录，而是标记为禁用状态
    merchant.status = 0
    
    db.commit()
    
    return True 